import ActionTypes from '../config/ActionTypes';
import ActionCodes from '../config/ActionCodes';
import { postFetch, getFetch } from '../utils/network/request/HttpExtension.js';
import { createAction } from 'redux-actions';
import Session from '../utils/SessionUtils';
import { AsyncStorage } from 'react-native';
let finalContactsArr = [];
let ORG_Name_Arr = [];

export function GetContacts() {
	return dispatch => {
		AsyncStorage.getItem('contacts')
			.then(contacts => {
				if (contacts && contacts.length > 0) {
					dispatch({
						type: ActionTypes.CONTACT + ActionTypes.FETCH_SUCCESS_SUFFIX,
						items: JSON.parse(contacts),
					});
				} else {
					dispatch({ type: ActionTypes.CONTACT + ActionTypes.FETCH_LOADING_SUFFIX });
					let orgID = 'f80fe6b0-4a83-46f5-b78c-a17cc49ad172';
					let param = {
						SearchType: '0',
						ORG_ID: orgID,
						// ORG_ID:Session.CurrentUser.orgId,
						USER_ID: Session.CurrentUser.USER_ID,
						GROUP_ID: '',
						PageSize: 50,
						DefaultGroup: 1,
						CONTACT_NAME: '',
						MAIL: '',
						MOBILE: '',
						POST: '',
						WORK_TEL: '',
					};

					postFetch(ActionCodes.contactList, param)
						.then(res => {
							finalContactsArr = [];

							if (res && JSON.stringify(res).indexOf('Public.E') < 0) {
								let contacts = res;
								fetchORG_NAME(contacts);

								filterContacts(contacts);

								AsyncStorage.setItem('contacts', JSON.stringify(finalContactsArr));
							}

							dispatch({
								type: ActionTypes.CONTACT + ActionTypes.FETCH_SUCCESS_SUFFIX,
								items: finalContactsArr,
							});
						})
						.catch(err => {
							alert(err);
							dispatch({ type: ActionTypes.CONTACT + ActionTypes.FETCH_ERROR_SUFFIX });
						});
				}
			})
			.catch(err => {
				alert('eee');
				// any exception including data not found
				// goes to catch()
				console.warn(err.message);

				switch (err.name) {
					case 'NotFoundError':
						break;
					case 'ExpiredError':
						// TODO
						break;
				}
			});
	};
}

const filterContacts = contactsArr => {
	(async () => {
		ORG_Name_Arr.forEach(org => {
			var contactObj = {};
			var filterItems = contactsArr.filter(filterItem => filterItem.ORG_NAME == org);
			contactObj.ORG_NAME = org;
			contactObj.items = filterItems;
			finalContactsArr.push(contactObj);
		});
	})();
};
const fetchORG_NAME = contactsArr => {
	(async () => {
		ORG_Name_Arr = contactsArr.map(item => item.ORG_NAME);
		ORG_Name_Arr = unique(ORG_Name_Arr);
	})();
};
const unique = arr => {
	var result = [],
		hash = {};
	for (var i = 0, elem; (elem = arr[i]) != null; i++) {
		if (!hash[elem]) {
			result.push(elem);
			hash[elem] = true;
		}
	}
	return result;
};
